const express = require('express');
const db = require('../db/db');
const config = require('../config')
const jwt = require('jsonwebtoken')
//路由
const router = express.Router();

router.use((req, res, next) => {
    // 检查是否为登录、注册或忘记密码接口
    if (req.path === '/login' || req.path === '/register' || req.path === '/forget') {
      next();
      return;
    }
  
    const token = req.headers.authorization;
    if (!token) {
      return res.status(401).send({ auth: false, message: 'No token provided.' });
    }
    // 使用 jwt.verify 验证 token
    jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
      if (err) {
        return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
      }
      // 将 userId 存储在 req.userId 中
      req.userId = decoded.id;
      next();
    });
  });
//登录验证
router.post('/login', (req, res) => {
    const { username, password } = req.body;
    const sql = 'select * from user where username =? and password = ?';
    db.query(sql, [username, password], (err, results) => {
      if (err) {
        return res.status(500).send({ message: '数据库错误' });
      }
      if (results.length > 0) {
        const user = {
          id: results[0].id,
          username: results[0].username,
        };
        // 生成 token
        const token = jwt.sign(user, config.jwtSecretKey, {
          expiresIn: config.expiresIn,
        });
        res.send({ status: 200, message: '登陆成功', token: 'Bearer ' + token });
      } else {
        res.send({ status: 401, message: '登录失败,账号或密码错误' });
      }
    });
  });

//修改密码
router.post('/pwd', (req, res) => {
    const { password, rpassword } = req.body;
    const userId = req.userId; // 使用 req.userId 获取用户标识
    // 先判断旧密码
    const checkpwdsql = 'select * from user where id = ?';
    db.query(checkpwdsql, [userId], (err, results) => {
        if (err) {
            return res.status(500).send({ message: '数据库错误' });
        }
        if (results.length === 0) {
            return res.status(401).send({ message: '用户不存在' });
        }
        const user = results[0];
        if (user.password != password) {
            return res.status(401).send({ message: '当前密码错误' });
        }
        // 如果旧密码正确则更新密码
        const sql = 'update user set password = ? where id = ?';
        db.query(sql, [rpassword, userId], (err, results) => {
            if (err) {
                return res.status(500).send({ message: '数据库错误' });
            }
            if (results.affectedRows > 0) {
                res.send({ status: 200, message: '修改成功' });
            } else {
                res.send({ status: 401, message: '修改失败' });
            }
        });
    });
});

//注册
// TODO: 单独将用户名判断独立出来
router.post('/register',(req,res)=>{
    const{username,password,phonenumber} = req.body;
    const checkuser = 'select * from user where username = ?'
    db.query(checkuser,[username],(err,results)=>{
        if(err) res.status(500).send({message:"服务器错误"})
        if(results.length > 0){
            return res.send({status:401,message:"账号存在"})
        }else{
            const sql = 'insert into user (username,password,phonenumber) values (?,?,?)'
            db.query(sql,[username,password,phonenumber],(err,results)=>{
                if(err){
                    return res.status(500).send({message:"注册失败,服务器错误"})
                }else{
                    return res.send({status:200,message:"注册成功"})
                }
            })
        }
    })
})

//忘记密码
router.post('/forget',(req,res)=>{
    const {username,password,phonenumber} = req.body;
    const check = 'select * from user where username=? and phonenumber=?'
    db.query(check,[username,phonenumber],(err,results)=>{
        console.log(results)
        if(err) res.status(500).send({message:"服务器错误"})
        if(results.length > 0){
            if(results[0].password == password){
                return res.status(401).send({message:"密码重复"})
            }
            const sql = 'update user set password=? where username = ?'
            db.query(sql,[password,username],(err,results)=>{
                if(err){
                    return res.status(500).send({message:"服务器错误,更新失败"})
                }
                else{
                    return res.send({status:200,message:"更新成功"})
                }
            })
        }
        else{
            return res.status(401).send({message:"信息填写错误"})
        }
    })
})
module.exports = router